package com.arron.juc;

/**
 * @Classname SemaphoreDemo
 * @Description TODO
 * @Date 2020/8/21 15:34
 * @Created by 刘
 */

import java.util.concurrent.Semaphore;
import java.util.concurrent.TimeUnit;

/**
 * 信号量
 */
public class SemaphoreDemo {

    /**
     * 模拟3个车位，10个人来抢车位
     * @param args
     */
    public static void main(String[] args) {

        Semaphore semaphore = new Semaphore(3);

         for (int i = 1; i <= 10; i++) {
             new Thread(()->{
                 try {
                     semaphore.acquire();
                     System.out.println(Thread.currentThread().getName()+"抢到车位，停3分钟");
                     TimeUnit.SECONDS.sleep(3);
                     System.out.println(Thread.currentThread().getName()+"离开车位。。");
                 } catch (Exception e) {
                     e.printStackTrace();
                 }finally {
                     semaphore.release();
                 }

             },String.valueOf(i)).start();
         }
    }

}
